package jxta.chat;

import java.io.IOException;

import jxta.chat.entities.AbstractMessage;
import jxta.chat.entities.LoginMessage;
import jxta.chat.entities.MessageParams;
import jxta.chat.events.JxtaChatEvent;
import jxta.chat.module.PipeModuleManager;
import jxta.chat.util.Constants.MessageParamsKeys;
import jxta.test.JxtaManager;
import net.jxta.document.AdvertisementFactory;
import net.jxta.document.MimeMediaType;
import net.jxta.document.StructuredDocument;
import net.jxta.document.StructuredDocumentFactory;
import net.jxta.document.XMLDocument;
import net.jxta.endpoint.Message;
import net.jxta.endpoint.MessageElement;
import net.jxta.peergroup.PeerGroup;
import net.jxta.pipe.PipeMsgEvent;
import net.jxta.pipe.PipeMsgListener;
import net.jxta.protocol.PipeAdvertisement;
import net.jxta.util.JxtaBiDiPipe;

public class LoginMessageHandler extends AbstractMessageHandler{
	
	@SuppressWarnings(value="unchecked")
	@Override
	public AbstractMessage handleMessage(Message msg, PeerGroup pg){
		
		LoginMessage lm = new LoginMessage(msg);
		MessageElement msgElement = lm.getPipeAdvertismentElement();
		String peerName = lm.getPeerName();
    	
    	if (msgElement != null){
    		System.out.println("Got bidi ADV: " + msgElement.toString());
    		
    		 StructuredDocument sd = null;

    	        try {
    	            sd = StructuredDocumentFactory.newStructuredDocument(MimeMediaType.XMLUTF8,
    	            		msgElement.getStream());
    	        } catch (IOException ioe) {
    	        	ioe.printStackTrace();
    	        }

    	        PipeAdvertisement pa = null;

    	        if (sd != null) {
    	            try {
    	                XMLDocument xml = (XMLDocument) StructuredDocumentFactory.newStructuredDocument( MimeMediaType.XMLUTF8, sd.getStream() );
    	                pa = (PipeAdvertisement) AdvertisementFactory.
    	                        newAdvertisement(xml);

    	            } catch (IOException ioe) {
    	            	ioe.printStackTrace();
    	            }
    	        }
    	        
    	        try {
					JxtaBiDiPipe pipe = new JxtaBiDiPipe(pg, pa,
							40 * 1000, null);
					
					BidiPipeListener listener = new BidiPipeListener();
					
					pipe.setMessageListener(listener);
					
					PipeHolder.getInstance().addPipe(peerName, pipe);
					
					// Notify the listeners about the new pipe
					JxtaChatEvent event = new JxtaChatEvent(lm, listener);
					notifyListeners(event);
					
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    	}
    	else{
    		System.out.println("no bidi pipe data");
    	}
    	
    	return null;
	}

	public void pipeMsgEvent(PipeMsgEvent event) {
		// TODO Auto-generated method stub
		
	}
	
}
